package ua.maxicash.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import ua.maxicash.vo.*;

@Repository("geoDao")
public class GeoDaoImpl implements GeoDao {

	@Autowired
	private HibernateTemplate hibernateTemplate;

	@Override
	public List<Country> getAllCountries() {

		//DetachedCriteria crit = DetachedCriteria.forClass(Country.class);
        //crit.setFetchMode("regions", FetchMode.SELECT);
		
		return hibernateTemplate.find("from Country");
	}

	@Override
	public Set<Region> getAllRegionsOfCountry(Long idCountry) {

		DetachedCriteria crit = DetachedCriteria.forClass(Region.class);
		crit.add(Restrictions.eq("country.idCountry",idCountry));
		return new HashSet<Region>(hibernateTemplate.findByCriteria(crit));

	}

	@Override
	public Set<City> getAllCitiesOfRegion(Long idRegion) {

		DetachedCriteria crit = DetachedCriteria.forClass(City.class);
		crit.add(Restrictions.eq("region.idRegion",idRegion));
		return new HashSet<City>(hibernateTemplate.findByCriteria(crit));
		
	}

	@Override
	public void addCountry(Country country) {
		hibernateTemplate.saveOrUpdate(country);
	}

	@Override
	public void addRegion(Region region) {
		hibernateTemplate.saveOrUpdate(region);

	}

	@Override
	public void addCity(City city) {
		hibernateTemplate.saveOrUpdate(city);

	}

	@Override
	public City getCityById(Long idCity) {
		DetachedCriteria criteria = DetachedCriteria.forClass(City.class);
		criteria.add(Restrictions.idEq(idCity));
		return (City) hibernateTemplate.findByCriteria(criteria).get(0);
		
	}

	@Override
	public Region getRegionById(Long idRegion) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Region.class);
		criteria.add(Restrictions.idEq(idRegion));
		return (Region) hibernateTemplate.findByCriteria(criteria).get(0);
	}

	@Override
	public Country getCountryById(Long idCountry) {
		DetachedCriteria criteria = DetachedCriteria.forClass(Country.class);
		criteria.add(Restrictions.idEq(idCountry));
		return (Country) hibernateTemplate.findByCriteria(criteria).get(0);
	}

    @Override
    public List<City> getCitiesLike(String term) {

        DetachedCriteria criteria = DetachedCriteria.forClass(City.class);
		criteria.add(Restrictions.or(Restrictions.ilike("ruName", term , MatchMode.ANYWHERE), Restrictions.ilike("enName",term,MatchMode.ANYWHERE)));
        return hibernateTemplate.findByCriteria(criteria);

    }
}
